#include <LitStdAfx.h>
#include "LitFileSystem.h"
#include <boost\filesystem.hpp>
namespace Lit
{	
	void FileSystem::_setApplicationPath( const std::string &str ){
		boost::filesystem::current_path( str );
	}
	std::string FileSystem::applicationPath(){ 
		return boost::filesystem::current_path().string();
	}
	bool FileSystem::exists( const std::string &name ){
		return boost::filesystem::exists(name);
	}
	void FileSystem::removeAll( const std::string &path ){
		boost::filesystem::remove_all(path);
	}
	bool FileSystem::createDirectories( const std::string &path ){
		try
		{
			if( !boost::filesystem::is_directory( path ) )
				boost::filesystem::create_directories( path );
		}
		catch( ... )
		{
			return false;
		}
		return true;
	}
	const ResourcesList& FileSystem::listResources() const{
		return mResources;
	}
	std::string FileSystem::fileName( const std::string &path ){
		std::string p = path;
		if( p.empty() ) return p;
		if( Ogre::StringUtil::endsWith( path, "/" ) ) p.erase( p.begin()+(p.size()-1) );
		return boost::filesystem::path(path).filename().string();
	}
	std::string FileSystem::dirName( const std::string &path ){
		std::string p = path;
		if( p.empty() ) return p;
		if( Ogre::StringUtil::endsWith( path, "/" ) ) p.erase( p.begin()+(p.size()-1) );
		std::string ret= boost::filesystem::path(path).parent_path().string();
		return ret;
	}
	FilePath FileSystem::findResourcePath( const std::string &res_name )
	{
		std::string resourceGroup;
		try{
			resourceGroup=Ogre::ResourceGroupManager::getSingletonPtr()->findGroupContainingResource(res_name);
		}catch(...){ return FilePath(); }
		Ogre::FileInfoListPtr fileInfoList(Ogre::ResourceGroupManager::getSingletonPtr()->findResourceFileInfo(resourceGroup, res_name));
		if( fileInfoList->empty() )
			return FilePath();
		Ogre::FileInfo &p(fileInfoList->at(0));
		if( !p.filename.empty() )
		{
			if( p.archive )
			{
				return FilePath(p.archive->getName()+"/"+p.filename);
			}
		}
		return FilePath();
	}
};